package com.jj.dao.impl;

import com.jj.dao.BaseDao;
import com.jj.dao.EmployeeDao;
import com.jj.entity.Department;
import com.jj.entity.Employee;

import java.sql.ResultSet;
import java.sql.SQLException;

public class EmployeeDaoImpl extends BaseDao implements EmployeeDao {
    @Override
    public Employee getEmployeeById(int id) {
        Employee employee = null;
        String sql = "SELECT e.*, d.dept_name FROM employee e " +
                "LEFT JOIN department d ON e.dept_id = d.id " +
                "WHERE e.id=?";
        ResultSet rs = executeQuery(sql, id);
        if(rs != null) {
            try {
                if(rs.next()) {
                    employee = new Employee();
                    employee.setId(rs.getInt("id"));
                    employee.setEmpName(rs.getString("emp_name"));
                    employee.setDeptId(rs.getInt("dept_id"));
                    employee.setPosition(rs.getString("position"));
                    employee.setOnboarding(rs.getDate("onboarding"));
                    employee.setPhone(rs.getString("phone"));
                    employee.setImgUrl(rs.getString("img_url"));

                    // 设置部门信息
                    Department department = new Department();
                    department.setId(rs.getInt("dept_id"));
                    department.setDeptName(rs.getString("dept_name"));
                    employee.setDepartment(department);
                }
            } catch (SQLException e) {
                throw new RuntimeException("获取员工信息失败", e);
            } finally {
                closedAll(rs);
            }
        }
        return employee;
    }

    @Override
    public int addEmployee(Employee employee) {
        String sql = "insert into employee(emp_name,dept_id,position,onboarding,phone,img_url) values(?,?,?,?,?,?)";
        return executeUpdate(sql,
                employee.getEmpName(),
                employee.getDeptId(),
                employee.getPosition(),
                employee.getOnboarding(),
                employee.getPhone(),
                employee.getImgUrl());
    }

    @Override
    public int updateEmployee(Employee employee) {
        String sql = "update employee set emp_name = ?,dept_id = ?,position = ?,onboarding = ?,phone = ?,img_url = ? where id = ?";
        return executeUpdate(sql,
                employee.getEmpName(),
                employee.getDeptId(),
                employee.getPosition(),
                employee.getOnboarding(),
                employee.getPhone(),
                employee.getImgUrl(),
                employee.getId()
        );
    }

    @Override
    public int deleteEmployee(int id) {
        String sql = "delete from employee where id = ?";
        return executeUpdate(sql,id);
    }
}
